import React, { useState, useRef, useEffect } from 'react';
import { connect, useDispatch } from 'umi';
import OrgTreeSelect from '@/components/OrgTreeSelect';
import { Drawer, Form, Button, Input, message, Select, Tooltip, TreeSelect } from 'antd';
import { QuestionCircleOutlined } from '@ant-design/icons';
import RoleAuthUsers from '../RoleAuthUsers';

const layout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 18 },
};
const validateMessages = {
  required: "'${label}' 是必填项！",
};
const { SHOW_ALL } = TreeSelect;

const RoleAddEdit = (props) => {
  const { drawerType, handleClose, editData = {}, appCodeOfSelect } = props;
  const [form] = Form.useForm();
  const dispatch = useDispatch();
  // const selectUsertRef = useRef();
  const [roleList, setRoleList] = useState([]);
  const [orgList, setOrgList] = useState([]);
  const [detail, setDetail] = useState({});
  const [, updateCmp] = useState(new Date());

  useEffect(() => {
    if (!editData.id) return;
    dispatch({
      type: 'commonRoleManageModel/getOrgRoleDtail',
      payload: { roleId: editData.id },
    }).then((res) => {
      if (res.code === 0) {
        const param = {
          ...res.data,
          orgIdList: res.data?.orgList?.map((it) => ({
            value: it.orgId,
            label: it.orgName,
          })),
          // orgIdList: res.data?.orgList?.map((o) => o.orgId)?.length > 0 && {
          //   value: res.data.orgList[0].orgId,
          //   label: res.data.orgList[0].orgName,
          // },
          inheritedPublicRoleId: res.data?.inheritedPublicRole?.roleId,
        };
        setDetail(param);
        form.setFieldsValue(param);
      }
    });
    return () => {};
  }, [editData]);

  useEffect(() => {
    dispatch({
      type: 'orgRoleManageModel/getAllRoleList',
      payload: { pageIndex: 1, pageSize: 1000000, appCode: appCodeOfSelect },
    }).then((res) => {
      if (res.code === 0) {
        setRoleList(res.data?.dataList);
      }
    });
    // dispatch({
    //   type: 'orgRoleManageModel/getAllOrgList',
    //   payload: { pageIndex: 1, pageSize: 1000000 },
    // }).then((res) => {
    //   if (res.code === 0) {
    //     setOrgList(
    //       listToTree(res.data?.dataList?.map((d) => ({ ...d, key: d.id, title: d.orgName }))),
    //     );
    //   }
    // });
    dispatch({
      type: 'orgManageModel/getOrgRootTree',
    }).then((data) => {
      setOrgList(data.map((d) => ({ ...d, isLeaf: !d.hasChild, key: d.id })));
    });
    return () => {};
  }, []);

  const listToTree = (list) => {
    let info = list.reduce((map, node) => {
      return (map[node.id] = node), (node.children = []), map;
    }, {});
    return list.filter((node) => {
      if (info[node.parentId]) {
        // 将对应的node放入对应的对象里面去，因为它是浅拷贝，所以会影响原来的数组
        // 进而组装成一个树结构，这块大家打印出来看看就明白了了
        info[node.parentId].children.push(node);
      }
      // 将没parentId的node返回组成一个新数组
      // 没有parentId代表着它是根元素
      return !node.parentId; // 为 true会返回这个数据，为false则不会返回
    });
  };

  const handleSubmit = () => {
    const { validateFields } = form;
    validateFields().then((values) => {
      const params = {
        // userIdList: selectUsertRef.current.getListOfSelectUserIds(),
        appCode: appCodeOfSelect,
        ...values,
        orgIdList: values.orgIdList?.map(it => it.value),
      };
      let dispatchType = 'orgRoleManageModel/addOrgRole';
      if (drawerType !== 'add') {
        params.id = editData.id;
        dispatchType = 'orgRoleManageModel/updateOrgRole';
      }
      dispatch({
        type: dispatchType,
        payload: params,
      }).then((res) => {
        const { code, message: errMsg } = res;
        if (code === 0) {
          message.success(`${drawerType === 'add' ? '新增' : '编辑'}成功`);
          handleClose(true);
        } else {
          message.error(errMsg);
        }
      });
    });
  };

  const orgChange = (val, rec) => {
    // form.setFieldsValue({
    //   orgIdList: [...list, { value: val, label: rec?.title }],
    // });
    setDetail({ ...detail, userList: [] });
    updateCmp(new Date());
  };

  const customizedSelectAll = (ids) => {
    const Fields = form.getFieldsValue();
    ids.forEach((item) => {
      if(!Fields.orgIdList) {
        Fields.orgIdList = [];
        Fields.orgIdList.push({
          value: item.value,
          label: item.title
        })
      }
      if(!Fields.orgIdList.find((it) => it.value === item.value)) {
        Fields.orgIdList.push({
          value: item.value,
          label: item.title
        })
      }
    });
    setDetail(Fields);
    form.setFieldsValue(Fields);
  }
  // const onLoadData = ({ id }) => {
  //   return new Promise((resolve) => {
  //     dispatch({
  //       type: 'orgManageModel/getChildOrgListByParentId',
  //       payload: {
  //         parentId: id,
  //       },
  //     }).then((data) => {
  //       console.log(data);
  //       setOrgList(
  //         orgList.concat(
  //           data.map((d) => ({ ...d, isLeaf: !d.hasChild, pId: d.parentId, key: d.id })),
  //         ),
  //       );
  //       resolve();
  //     });
  //   });
  // };

  return (
    <Drawer
      title={`${drawerType === 'add' ? '添加' : '修改'}角色`}
      width={600}
      visible
      onClose={() => handleClose()}
      bodyStyle={{ paddingBottom: 80 }}
      footer={
        <div style={{ textAlign: 'right' }}>
          <Button onClick={() => handleClose()} style={{ marginRight: 8 }}>
            {' '}
            取消
          </Button>
          <Button type="primary" onClick={handleSubmit}>
            {drawerType === 'add' ? '添加' : '保存'}
          </Button>
        </div>
      }
    >
      <Form {...layout} form={form} name="nest-messages" validateMessages={validateMessages}>
        <div style={{ marginBottom: 12, fontWeight: 'bold' }}>基本信息</div>
        <Form.Item name="roleCode" label="角色编号" rules={[{ required: true }]}>
          <Input placeholder="输入角色编号" />
        </Form.Item>
        <Form.Item name="roleName" label="角色名称" rules={[{ required: true }]}>
          <Input placeholder="输入角色名称" />
        </Form.Item>
        <Form.Item name="roleType" label="角色类型" rules={[{ required: true }]} initialValue={1}>
          <Select placeholder="选择角色类型" disabled>
            <Select.Option value={1}>组织角色</Select.Option>
          </Select>
        </Form.Item>
        <Form.Item name="orgIdList" label="适用组织">
          {/* <TreeSelect
            treeDataSimpleMode
            getPopupContainer={(ele) => ele.parentNode}
            style={{ width: '100%' }}
            labelInValue
            // dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
            placeholder="选择适用组织"
            onChange={orgChange}
            loadData={onLoadData}
            treeData={orgList}
          /> */}
          <OrgTreeSelect
            allowClear
            labelInValue
            style={{ width: '100%' }}
            placeholder="请选择"
            dropdownMatchSelectWidth={false}
            dropdownStyle={{ maxWidth: 400 }}
            onSelect={orgChange}
            // disabled={!!editData?.id}
            treeCheckable={true}
            treeCheckStrictly={true}
            showCheckedStrategy={SHOW_ALL}
            customizedSelectAll={customizedSelectAll}
            isOpencustomizedSelectAll={true}
          />
          {/* <Select placeholder="选择适用组织" allowClear onChange={() => updateCmp(new Date())}>
            {orgList.map((org) => (
              <Select.Option key={org.id} value={org.id}>
                {org.orgName}
              </Select.Option>
            ))}
          </Select> */}
        </Form.Item>
        <Form.Item name="inheritedPublicRoleId" label="公共角色" rules={[{ required: false }]}>
          <Select
            placeholder="选择公共角色"
            style={{ width: '90%' }}
            disabled={!!editData?.id}
            showSearch
            allowClear
          >
            {roleList.map((role) => (
              <Select.Option key={role.id} value={role.id}>
                {role.roleName}
              </Select.Option>
            ))}
          </Select>
        </Form.Item>
        <Form.Item wrapperCol={{ offset: 22, span: 1 }} style={{ marginTop: -56 }}>
          <Tooltip title="用于权限初始化">
            <QuestionCircleOutlined style={{ padding: '10px 15px', cursor: 'pointer' }} />
          </Tooltip>
        </Form.Item>
        <Form.Item name="roleDesc" label="描述">
          <Input.TextArea rows={5} maxLength={255} placeholder="输入描述，限255字" />
        </Form.Item>
      </Form>
      {/* <RoleAuthUsers
        ref={selectUsertRef}
        userList={detail.userList || []}
        orgId={form.getFieldValue('orgIdList')?.value}
        title="授权用户"
        style={{ marginTop: 38 }}
        tbodyStyle={{ height: 410 }}
      /> */}
    </Drawer>
  );
};

export default connect((state) => state)(RoleAddEdit);
